import { Router, Request } from "express";
import { AuthUser } from "./types";
import { prisma } from "./db";
import { ROLE } from "./enum";
import { authList } from "./ram";

export const mainrouter = Router();

mainrouter.get("/", (req, res) => {
    if (authList[req.cookies.auth] === undefined || authList[req.cookies.auth] === undefined) {
        res.render("auth");
    } else {
        const u = authList[req.cookies.auth];
        res.render("index", { isStudent: u.role == ROLE.STUDENT });
    }
});

mainrouter.post("/auth", async (req: Request<{}, {}, AuthUser>, res) => {
    const u = await prisma.user.findFirst({ where: { login: req.body.login } });
    if (u !== null) {
        const key = (new Date()).toISOString();
        res.cookie("auth", key);
        authList[key] = u;
        res.json({ res: "ok", u: u });
    }
    else
        res.json({ res: "bad", text: "Неверный логин или пароль" });
});

mainrouter.post("/exit", async (req, res) => {
    if (authList[req.cookies.auth] !== undefined && authList[req.cookies.auth] !== undefined) {
        res.cookie("auth", "", { expires: new Date() });
        delete authList[req.cookies.auth];
        res.json({ res: "ok" });
    } else
        res.json({ res: "bad", text: "Авторизация не найдена" });
});